package com.sky.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.wu
 * @Data #{DATE} #{TIME}
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final  String DISH_LIST="dish_list:";
    @Transactional
    @Override
    public int add(DishDTO dishDTO) {
        //删除redis中缓存的菜品数据
        removeRedis();

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        if (!dishMapper.add(dish)) {
            throw new BaseException("新增菜品信息失败");
        }
        Setmeal setmeal = setmealMapper.getSetmeal(dish.getCategoryId());
        if (setmeal != null) {
            SetmealDish s = new SetmealDish();
            s.setDishId(dish.getId());
            s.setName(dish.getName());
            s.setSetmealId(setmeal.getId());
            s.setPrice(setmeal.getPrice());
            setmealDishMapper.add(s);
        }
        //获取insert语句生成的主键值
        Long dishId = dish.getId();
        List<DishFlavor> list = dishDTO.getFlavors();
        list.forEach(x -> {
            x.setDishId(dishId);
        });
        return dishFlavorMapper.insert(list);
    }

    @Override
    public PageResult getPage(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<DishVO> list = dishMapper.getPage(dto);
        Page<DishVO> page = (Page) list;
        Long total = page.getTotal();
        List<DishVO> result = page.getResult();
        return new PageResult(total, result);
    }

    @Override
    public void delete(List<Integer> ids) {

        //删除redis中缓存的菜品数据
        removeRedis();

        ids.forEach(id -> {
            List<SetmealDish> list = setmealDishMapper.getSetmealDish(id);
            if (list.size() > 0) {
                throw new BaseException("删除菜品失败,不能直接删除套餐里的菜品");
            }
        });
        if (dishMapper.delete(ids) != ids.size()) {
            throw new BaseException("删除菜品失败,不能删除起售的菜品");
        }
        ids.forEach(id -> {
            dishFlavorMapper.deleteFlavor(id);
        });
    }

    @Override
    public void update(DishDTO dishDTO) {
        //删除redis中缓存的菜品数据
        removeRedis();

        DishVO d = dishMapper.selectById(dishDTO.getId());
        if (d == null) {
            throw new BaseException("菜品数据不存在，无法修改");
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        List<DishFlavor> flavor = dishFlavorMapper.getByDishId(dish.getId().intValue());
        if (flavor.size() > 0) {
            //删除菜品口味
            dishFlavorMapper.deleteByDishId(dishDTO.getId());
            //保存菜品口味
            dishFlavorMapper.insert(dishDTO.getFlavors());
        }
    }

    @Override
    public DishVO getById(Integer id) {
        DishVO dish = dishMapper.selectById(id.longValue());
        List<DishFlavor> flavor = dishFlavorMapper.getByDishId(id);
        dish.setFlavors(flavor);
        return dish;
    }

    @Override
    public int updateStatus(Long id, Integer status) {
        //删除redis中缓存的菜品数据
        removeRedis();

        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        return dishMapper.update(dish);
    }


    /**
     * 新增套餐根据id回显菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getDish(Long categoryId) {
        List<Dish> dish = dishMapper.getDish(categoryId);
        return dish;
    }

    /**
     * PC端 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getPcDish(Long categoryId) {
        String jsonStr = (String) redisTemplate.opsForHash().get(DISH_LIST, DISH_LIST + categoryId);
        if(!StringUtils.isEmpty(jsonStr)){
            List<DishVO> dishVOS = JSON.parseArray(jsonStr, DishVO.class);
            return dishVOS;
        }

        List<Dish> dish = dishMapper.getDish(categoryId);
        if (dish == null) {
            return Collections.emptyList();
        }

        List<DishVO> voList = dish.stream().map(x -> {
            DishVO vo = new DishVO();
            List<DishFlavor> list = dishFlavorMapper.getPcDishFlavors(x.getId());
            BeanUtils.copyProperties(x, vo);
            vo.setFlavors(list);
            return vo;
        }).collect(Collectors.toList());
        String jsonString = JSON.toJSONString(voList);
        redisTemplate.opsForHash().put(DISH_LIST, DISH_LIST+categoryId, jsonString);
        return voList;
    }

    public void removeRedis(){
        redisTemplate.delete(DISH_LIST);
    }
}
